package org.jeecgframework.web.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mybatis.ext.WiseCoreService;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.WxCommonService;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyContactsServiceI;
import org.jeecgframework.web.service.impl.ZyContactsServiceImpl;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.sendWxMessage;
import org.jeecgframework.workflow.pojo.base.TSBaseBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fr.third.org.apache.poi.hssf.record.formula.functions.IsNa;



/**
 * @Title: Controller
 * @Description: 联系人
 * @author ZhangYunlong
 * @date 2016-04-15 16:48:01
 * @version V1.0
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyContactsController")
public class ZyContactsController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyContactsController.class);

	@Autowired
	private ZyContactsServiceI zyContactsService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private WiseCoreService wiseCoreService;
	@Autowired
	private ZyCommonService zyCommonService;
	private String message;
	@Autowired
	private WxCommonService wxCommonService;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 联系人列表 页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "zyContacts")
	public ModelAndView zyContacts(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_contacts/zyContactsList");
	}

	/**
	 * @author ZhangYunlong
	 * 2016-4-20 下午4:58:24
	 * Description 弹出式系统用户选择页
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "zySysUsers")
	public ModelAndView zySysUsers(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_contacts/zyChooseSysUsers");
	}

	/**
	 * @author xiul
	 * 2016-8-15 下午2:33:31
	 * Description 工程师选择关联系统用户弹出页 datagrid
	 */
	@RequestMapping(params = "zySysUsersDatagrid")
	public void datagrid(TSUser user,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
		cq.add(Restrictions.eq("status", Short.valueOf("1")));
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);
		cq.add();
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}


	/**
	 * @author ZhangYunlong
	 * 2016-4-20 下午4:58:24
	 * Description 弹出式机构选择页
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "zyOrgs")
	public ModelAndView zyOrgs(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_contacts/zyChooseOrgs");
	}

	/**
	 * @author xiul
	 * 2016-6-16 下午5:22:35
	 * Description 弹出式机构选择页 - datagrid
	 */
	@RequestMapping(params = "chooseDepartListDatagrid")
	public void chooseDepartListDatagrid(TSDepart tsDepart,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
		cq.add(Restrictions.or(Restrictions.eq("logicDelete", "0"),Restrictions.isNull("logicDelete")));//基本过滤条件，只查询未删除的数据
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tsDepart, request.getParameterMap());
		cq.add();
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * easyui AJAX请求数据
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(ZyContactsEntity zyContacts,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		Map param = new HashMap<>();
		CriteriaQuery cq = new CriteriaQuery(ZyContactsEntity.class, dataGrid);
		cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"),Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
		// Add start 没有检索条件时不检索内容 Amy 2018/3/9
		boolean flag = false;
		Map<String, String[]> parameterMap = request.getParameterMap();
		for (String key : parameterMap.keySet()) {
			if(key.equals("type") || key.equals("cinemaName") || key.equals("belongOrgName") || key.equals("belongCinemaId")
					|| key.equals("name") || key.equals("cellphone1") || key.equals("state")|| key.equals("position")|| key.equals("authenticationLevel")){
				if(!StringUtil.isEmpty(parameterMap.get(key)[0])){
					flag = true;//页面 查询条件为空不做查询
					break;
				}
			}
		}
		// Add End 没有检索条件时不检索内容 Amy 2018/3/9
		if(flag){
//			//影院查看页面
//			String belongCinemaId = oConvertUtils.getString(request.getParameter("belongCinemaId"));
//			if(StringUtil.isNotEmpty(belongCinemaId)){
//				cq.eq("belongCinema.id", belongCinemaId);
//			}
//			//查询条件组装器
//			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyContacts, request.getParameterMap());
//			try{
//			//自定义追加查询条件
//			}catch (Exception e) {
//				throw new BusinessException(e.getMessage());
//			}
//			cq.add();
//			this.zyContactsService.getDataGridReturn(cq, true);

			for (Object key : request.getParameterMap().keySet()) {
				if ((String[]) request.getParameterMap().get(key) != null) {
					for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
						if (((String[]) request.getParameterMap().get(key))[i] != null) {
							param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
						}
					}
				}
			}

			wiseCoreService.selectDataGrid("selectContactsDatagrid", param, dataGrid);
		} else{
			dataGrid.setResults(new ArrayList<>());
		}
		TagUtil.datagrid(response, dataGrid);
	}


	/**
	 * 逻辑删除联系人
	 */
	@RequestMapping(params = "dologicDel")
	@ResponseBody
	public AjaxJson dologicDel(ZyContactsEntity zyContacts, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		zyContacts = systemService.getEntity(ZyContactsEntity.class, zyContacts.getId());
		message = "联系人["+zyContacts.getName()+"]删除成功";
		try{
			zyContacts.setIsDelete("1");
			zyContactsService.saveOrUpdate(zyContacts);
			ZyContactsHisEntity zyContactsHis = new ZyContactsHisEntity();
			MyBeanUtils.copyBeanNotNull2Bean(zyContacts, zyContactsHis);
			zyContactsHis.setDataStatus("delete");
			zyContactsHis.setBusId(zyContacts.getId());
			zyContactsService.save(zyContactsHis);
		}catch(Exception e){
			e.printStackTrace();
			message = "联系人["+zyContacts.getName()+"]删除失败";
		}
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}

	public void authContact(String contactId,String auth) throws Exception{
		
		try {
			ZyContactsEntity contact = systemService.get(ZyContactsEntity.class, contactId);
			if (null == contact) {
				return;
			}
			if (StringUtil.isEmpty(contact.getCellphone1())) {
				return;
			}
			if ("1".equals(contact.getAuthentication())) {
				String realName = contact.getName().trim();
				List<TSUser> users = systemService.findHql("from TSUser where realName=? and mobilePhone=?",realName, contact.getCellphone1());
				TSUser user = null;
				if (users.size() > 0) {
					user = users.get(0);
					user.setAuthenticationLevel("2");
					systemService.saveOrUpdate(user);
				} else {
					user = new TSUser();
					user.setRealName(realName);
					String userName = PinyinUtil.getPinYin(realName);
					user.setUserName(userName);
					List<TSUser> repeatUserList = systemService.findHql("from TSUser where userName = ?", userName);
					if (repeatUserList.size() > 0) {
						Integer num = repeatUserList.size() == 1 ? 1
								: repeatUserList.size() + 1;
						userName = userName + num;
					}
					user.setUserName(userName);
					user.setPassword(PasswordUtil.encrypt(user.getUserName(),"123456", PasswordUtil.getStaticSalt()));
					user.setAppPassword(user.getPassword());
					user.setStatus(Globals.User_Normal);
					user.setActivitiSync((short) 0);
					user.setAuthenticationLevel("2");
					user.setMobilePhone(contact.getCellphone1());
					user.setUserKey("");
					systemService.save(user);
				}
				contact.setTsBaseUser(user);
				systemService.saveOrUpdate(contact);

				// add start 181102 增加通知微信用户级别升级钻石
				if (user != null && user.getOpenId() != null && user.getOpenId() != "")
				{
					wxCommonService.noticeAddLevel(user.getOpenId(),"PROMOTE_DIAMOND");
				}
				// add end 181102

			}/*不知道下边的else是谁写的和干什么的*/
			/*else{
			    String userId = "";
			    if(contact.getTsBaseUser() != null){
			        userId = contact.getTsBaseUser().getId();
			        TSUser user = systemService.get(TSUser.class,userId);
			        systemService.saveOrUpdate(user);
			    }
			    contact.setTsBaseUser(null);
			    systemService.saveOrUpdate(contact);
			}*/
		} catch (Exception e) {
			throw e;
		}

	}


	/**
	 * 添加联系人
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZyContactsEntity zyContacts, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "联系人["+zyContacts.getName()+"]添加成功";
		try{
			if(zyContacts.getBelongCinema()!=null && zyContacts.getBelongCinema().getId().equals("")){
				zyContacts.setBelongCinema(null);
			}
			if(zyContacts.getBelongOrg() != null && zyContacts.getBelongOrg().getId().equals("")){
				zyContacts.setBelongOrg(null);
			}
			if(zyContacts.getTsBaseUser() != null && zyContacts.getTsBaseUser().getId().equals("")){
				zyContacts.setTsBaseUser(null);
			}
			zyContacts.setIsDelete("0");
			String cellPhone1 = zyContacts.getCellphone1();
			boolean flag = true;
			if(StringUtil.isNotEmpty(cellPhone1) && null != zyContacts.getTsBaseUser()){
				List<TSUser> users = systemService.findByProperty(TSUser.class, "mobilePhone", cellPhone1);
				if(null != users){
					if(users.size() == 1){
						if(!users.get(0).getId().equals(zyContacts.getTsBaseUser().getId())){
							flag = false;
							message = "系统用户已经存在当前手机号";
						}
					}else if(users.size() > 1){
						flag = false;
						message = "系统用户已经存在当前手机号";
					}
				}
			}
			j.setSuccess(flag);
			if(flag){
				zyContactsService.save(zyContacts);
				ZyContactsHisEntity zyContactsHis = new ZyContactsHisEntity();
				MyBeanUtils.copyBeanNotNull2Bean(zyContacts, zyContactsHis);
				zyContactsHis.setDataStatus("create");
				zyContactsHis.setBusId(zyContacts.getId());
				zyContactsService.save(zyContactsHis);
				//更新关联系统用户
				if(StringUtil.isNotEmpty(cellPhone1) && null != zyContacts.getTsBaseUser() && StringUtil.isNotEmpty(zyContacts.getTsBaseUser().getId())){
					//更新系统用户的电话
					TSUser user = systemService.get(TSUser.class, zyContacts.getTsBaseUser().getId());
					String oldPhoneNum = user.getMobilePhone();
					user.setMobilePhone(cellPhone1);
					systemService.saveOrUpdate(user);
					systemService.addLog("新增联系人时后台更新关联的系统用户[" + user.getUserName() + "]的手机号，由[" + oldPhoneNum + "]更新为：" + cellPhone1, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
				}
			}
			authContact(zyContacts.getId(),zyContacts.getAuthentication());
		}catch(Exception e){
			e.printStackTrace();
			message = "联系人["+zyContacts.getName()+"]添加失败";
		}
		systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}

	public void updateBindCinema(String userName,String cinemaName){
		if(StringUtil.isEmpty(userName)){
			return;
		}
		List<CbsWxUserBindEntity> bindEntities = systemService.findHql("from CbsWxUserBindEntity where userName=?", userName);
		for(CbsWxUserBindEntity bind : bindEntities){
			bind.setCinemaName(cinemaName);
			systemService.updateEntitie(bind);
		}
	}

	/**
	 * 更新联系人
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(ZyContactsEntity zyContacts, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		ZyContactsEntity t = zyContactsService.get(ZyContactsEntity.class, zyContacts.getId());
		String name = t.getName();
		message = "联系人[" + name + "]更新成功";
		if(zyContacts.getBelongCinema().getId().equals("")){
			zyContacts.setBelongCinema(null);
		}
		if(zyContacts.getBelongOrg().getId().equals("")){
			zyContacts.setBelongOrg(null);
		}
		if(zyContacts.getTsBaseUser().getId().equals("")){
			zyContacts.setTsBaseUser(null);
		}

		try {
			String cellPhone1 = zyContacts.getCellphone1();
			boolean flag = true;
			if(StringUtil.isNotEmpty(cellPhone1) && null != zyContacts.getTsBaseUser()){
				List<TSUser> users = systemService.findByProperty(TSUser.class, "mobilePhone", cellPhone1);
				if(null != users){
					if(users.size() == 1){
						if(!users.get(0).getId().equals(zyContacts.getTsBaseUser().getId())){
							flag = false;
							message = "系统用户已经存在当前手机号";
						}
					}else if(users.size() > 1){
						flag = false;
						message = "系统用户已经存在当前手机号";
					}
				}
			}
			j.setSuccess(flag);
			if(flag){
				if(null == zyContacts.getConBusiness()){
					zyContacts.setConBusiness("");
				}
				MyBeanUtils.copyBeanNotNull2Bean(zyContacts, t);
				if(zyContacts.getBelongCinema() == null){
					t.setBelongCinema(null);
				}
				if(zyContacts.getBelongOrg() == null){
					t.setBelongOrg(null);
				}
				if(zyContacts.getTsBaseUser() == null){
					t.setTsBaseUser(null);
				}
				systemService.saveOrUpdate(t);
				try{
					if(StringUtil.isNotEmpty(t.getTsBaseUser())){
						String userName = t.getTsBaseUser().getUserName();
						if(StringUtil.isNotEmpty(userName)){
							ZyCinemaEntity zc = zyContactsService.get(ZyCinemaEntity.class, zyContacts.getBelongCinema().getId());
							if(null != zc){
								updateBindCinema(userName,zc.getName());
							}
						}
					}
				}catch (Exception e){
					logger.info(e.getMessage());
				}

				ZyContactsHisEntity zyContactsHis = new ZyContactsHisEntity();
				MyBeanUtils.copyBeanNotNull2Bean(t, zyContactsHis);
				zyContactsHis.setDataStatus("update");
				zyContactsHis.setBusId(t.getId());
				systemService.save(zyContactsHis);





				/**微信绑定信息也调用该页面，处理微信用户信息用*/
				String wxBindId = request.getParameter("wxBindId");
				if(StringUtil.isEmpty(wxBindId)){
					authContact(zyContacts.getId(),zyContacts.getAuthentication());
				}
				if(StringUtil.isNotEmpty(wxBindId)){
					String wxAuthType = request.getParameter("wxAuthType");
					CbsWxUserBindEntity userBind = systemService.get(CbsWxUserBindEntity.class, wxBindId);
					if(null != zyContacts.getBelongCinema() && !StringUtil.isEmpty(zyContacts.getBelongCinema().getId())){
						ZyCinemaEntity cinema = systemService.get(ZyCinemaEntity.class,zyContacts.getBelongCinema().getId());
						userBind.setCinemaName(cinema.getName());
					}
					userBind.setPhoneNumber(zyContacts.getCellphone1());
					userBind.setEmail(zyContacts.getEmail());
					userBind.setApprovalStatus(wxAuthType);
					systemService.saveOrUpdate(userBind);
					List<TSBaseUser> userList = systemService.findHql("from TSBaseUser where openId = ?", userBind.getOpenId());
					if(userList.size() > 0){
						if("1".equals(wxAuthType)){
							userList.get(0).setAuthenticationLevel("2");
							//升级钻石调用微信接口通知微信方升级该用户
							wxCommonService.noticeAddLevel(userList.get(0).getOpenId(),"PROMOTE_DIAMOND");
							//sendWxMsg(userList.get(0),userBind);
	                        //调用微信接口发送
	                        List<Map<String, String>> list = new ArrayList<>();
	                        if (StringUtil.isNotEmpty(userList.get(0).getOpenId())) {
	                            Map<String, String> map1 = new HashMap<>();
	                            map1.put("openid", userList.get(0).getOpenId());
	                            map1.put("message", "尊敬的客户，您的认证申请已通过，恭喜您升级为中影巴可钻石客户。");
	                            list.add(map1);
	                            wxCommonService.sendMsgForWx(list);
	                        }
						}/*else{
							userList.get(0).setAuthenticationLevel("1");
						}*/
						systemService.saveOrUpdate(userList.get(0));
					}
				}

				if(StringUtil.isNotEmpty(cellPhone1)){
					//更新系统用户的电话
					if(null != zyContacts.getTsBaseUser() && StringUtil.isNotEmpty(zyContacts.getTsBaseUser().getId())){
						TSUser user = systemService.get(TSUser.class, zyContacts.getTsBaseUser().getId());
						String oldPhoneNum = user.getMobilePhone();
						user.setMobilePhone(cellPhone1);
						systemService.saveOrUpdate(user);
						systemService.addLog("更新联系人时后台更新关联的系统用户[" + user.getUserName() + "]的手机号，由[" + oldPhoneNum + "]更新为：" + cellPhone1, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "联系人[" + name + "]更新失败";
		}
		systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}

	public void sendWxMsg(TSBaseUser user,CbsWxUserBindEntity userBind) throws Exception{
		//调用微信端接口发送微信模板推送消息
		List<Map<String,String>> list=new ArrayList<>();
		String openId=user.getOpenId();
		String content="";
		if(StringUtil.isNotEmpty(openId)){
			Map<String,String> map=new HashMap<>();
			map.put("openid",openId);
			map.put("message",content);
			list.add(map);
		}
		wxCommonService.sendMsgForWx(list);
	}

	/**
	 * @author xiul
	 * 2016-6-23 下午1:41:54
	 * Description 新增 更新之前 检查当前 联系人 所属机构下是否已经有巡检负责人 
	 */
	@ResponseBody
	@RequestMapping(params="checkTpIpHeaderUnique")
	public AjaxJson checkTpIpHeaderUnique(@RequestParam(value="belongOrg")String belongOrg,
										  @RequestParam(value="type")String type,
										  @RequestParam(value="id",required=false)String id){
		AjaxJson j = new AjaxJson();
		message = "检查通过";
		boolean flag = true;
		try {
			String name = null;
			if(type.equals("update")){
				name = zyContactsService.checkTpIpHeaderUnique(belongOrg,id);
			}else if(type.equals("add")){
				name = zyContactsService.checkTpIpHeaderUnique(belongOrg,null);
			}
			if(StringUtil.isNotEmpty(name)){
				flag = false;
				message = "当前机构下存在巡检联系人["+name+"]";
			}
		} catch (Exception e) {
			flag = false;
			message = "出现异常";
			e.printStackTrace();
		}
		j.setMsg(message);
		j.setSuccess(flag);
		return j;
	}

	/**
	 * @author xiul
	 * 2016-6-23 下午1:41:54
	 * Description 新增 更新之前 检查当前联系人 所属 影院下是否已经有巡检负责人 
	 */
	@ResponseBody
	@RequestMapping(params="checkCmIpHeaderUnique")
	public AjaxJson checkCmIpHeaderUnique(@RequestParam(value="belongCinema")String belongCinema,
										  @RequestParam(value="id",required=false)String id){
		AjaxJson j = new AjaxJson();
		message = "检查通过";
		boolean flag = true;
		try {
			String name = null;
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT COUNT(1) AS total,name ");
			sql.append(" FROM zy_contacts ");
			sql.append(" WHERE ");
			sql.append(" belong_cinema = '"+belongCinema+"'");
			sql.append(" AND position = '"+StaticValue.DIC_CONTACT_POSITION_C_MANAGER+"'");
			sql.append(" AND con_business LIKE '%"+StaticValue.DIC_BUS_SCOPE_INSPECTION+"%' ");
			sql.append(" AND state = '"+StaticValue.DIC_ENGINEER_STATE_ONJOB+"' ");
			sql.append(" AND is_delete = 0 ");
			if(id != null){
				sql.append(" AND id != '"+id+"' ");
			}
			List<Map<String,Object>> mapList = systemService.findForJdbc(sql.toString());

			if(null != mapList && mapList.size() > 0 && Integer.valueOf(mapList.get(0).get("total").toString()) > 0){
				name = mapList.get(0).get("name").toString();
			}

			if(StringUtil.isNotEmpty(name)){
				flag = false;
				message = "当前影院下存在巡检联系人["+name+"]";
			}
		} catch (Exception e) {
			flag = false;
			message = "出现异常";
			e.printStackTrace();
		}
		j.setMsg(message);
		j.setSuccess(flag);
		return j;
	}

	/**
	 * @author xiul
	 * 2016-6-23 下午1:41:54
	 * Description 新增 更新之前 检查当前 联系人是否重复
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params="checkCtUnique")
	public AjaxJson checkCtUnique(@RequestParam(value="type")String type,
								  @RequestParam(value="id",required = false)String id,
								  @RequestParam(value="name")String name,
								  @RequestParam(value="cellphone1")String cellphone1){
		AjaxJson j = new AjaxJson();
		try {
			boolean flag = true;
			j.setMsg("联系人["+name+"]已经存在");
			if(type.equals("update")){
				flag = zyContactsService.checkCtUnique(name,cellphone1,id);
			}else if(type.equals("add")){
				flag = zyContactsService.checkCtUnique(name,cellphone1,null);
			}
			j.setSuccess(flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * @author xiul
	 * 2016-7-7 下午12:12:33
	 * Description 检查关联系统用户 是否已经被关联过
	 * @param baseId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params="checkLinkSysUserUnique")
	public AjaxJson checkLinkSysUserUnique(
			@RequestParam(value="id",required = false)String id,
			@RequestParam(value="baseId")String baseId){
		AjaxJson j = new AjaxJson();
		boolean flag = true;
		try {
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT t.name ");
			sql.append(" FROM zy_contacts t");
			sql.append(" WHERE ");
			sql.append(" t.base_id = '"+ baseId +"' ");
			if(StringUtil.isNotEmpty(id)){
				sql.append(" AND t.id != '"+ id +"' ");
			}
			List<Map<String, Object>> mapList = zyCommonService.findForJdbc(sql.toString());
			if(mapList.size() > 0){
				message = "当前关联的系统用户已经["+ mapList.get(0).get("name") +"]被关联过";
				flag = false;
			}
		} catch (Exception e) {
			message = "检查关联系统用户异常";
			flag = false;
			e.printStackTrace();
		}
		j.setMsg(message);
		j.setSuccess(flag);
		return j;
	}

	/**
	 * 联系人新增页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(ZyContactsEntity zyContacts, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyContacts.getId())) {
			zyContacts = zyContactsService.getEntity(ZyContactsEntity.class, zyContacts.getId());
			req.setAttribute("zyContactsPage", zyContacts);
		}
		return new ModelAndView("com/zybk/zy_contacts/zyContacts-add");
	}
	/**
	 * 联系人编辑页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(ZyContactsEntity zyContacts, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyContacts.getId())) {
			zyContacts = zyContactsService.getEntity(ZyContactsEntity.class, zyContacts.getId());
			req.setAttribute("zyContactsPage", zyContacts);
		}
		return new ModelAndView("com/zybk/zy_contacts/zyContacts-update");
	}

	/**
	 * 联系人查看页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goView")
	public ModelAndView goView(ZyContactsEntity zyContacts, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyContacts.getId())) {
			zyContacts = zyContactsService.getEntity(ZyContactsEntity.class, zyContacts.getId());
			req.setAttribute("zyContactsPage", zyContacts);
		}
		return new ModelAndView("com/zybk/zy_contacts/zyContacts-view");
	}

	@RequestMapping(params = "setState")
	@ResponseBody
	public AjaxJson setContactState(String id,String state){
		AjaxJson result = new AjaxJson();
		if(StringUtil.isEmpty(state)){
			result.setSuccess(false);
			return result;
		}
		ZyContactsEntity ct = zyContactsService.get(ZyContactsEntity.class,oConvertUtils.getString(id));
		if (ct == null) {
			result.setSuccess(false);
			return result;
		}
		ct.setState(state);
		try{
			zyContactsService.updateEntitie(ct);
		}catch (Exception e){
			logger.info(e.getMessage());
			result.setSuccess(false);
		}
		return result;
	}

	@RequestMapping(params = "goWxContactsList")
	public ModelAndView wxContactsList(){
		ModelAndView mv = new ModelAndView("com/wx/personal_center/contacts/contact_list");
		TSUser user = ResourceUtil.getSessionUserName();
		ZyContactsEntity contact = zyContactsService.findContactByUserName(user.getUserName());
		mv.addObject("ct",contact);
		if(user.ifGoldMedal()){
			mv.addObject("showEdit",1);
		}
		return mv;
	}
	@RequestMapping(params = "goWxEdit")
	public ModelAndView goWxEdit(String id){
		ModelAndView mv = new ModelAndView("com/wx/personal_center/contacts/contact_edit");
		TSUser user = ResourceUtil.getSessionUserName();
		ZyContactsEntity contact = zyContactsService.findContactByUserName(user.getUserName());
		mv.addObject("ct",contact);
		return mv;
	}
	@RequestMapping(params = "wxUpdate")
	@ResponseBody
	public AjaxJson wxUpdate(ZyContactsEntity ct){
		AjaxJson result = new AjaxJson();
		if(!StringUtil.isEmpty(ct.getId())){
			ZyContactsEntity contact = systemService.get(ZyContactsEntity.class,ct.getId());
			contact.setName(ct.getName());
			contact.setTelephone(ct.getTelephone());
			contact.setPosition(ct.getPosition());
			contact.setState(ct.getState());
			contact.setFax(ct.getFax());
			contact.setEmail(ct.getEmail());
			systemService.saveOrUpdate(contact);
		}
		return result;
	}

	@RequestMapping(params = "search")
	@ResponseBody
	public List<ZyContactsServiceImpl.ZyContactsVo> search(String searchContent){
		String userName = ResourceUtil.getSessionUserName().getUserName();
		ZyContactsEntity ct = zyContactsService.findContactByUserName(userName);
		List<ZyContactsServiceImpl.ZyContactsVo> ctVo = new ArrayList<ZyContactsServiceImpl.ZyContactsVo>();
		if (ct != null) {
			List<ZyContactsEntity> cts = zyContactsService.findContactsInSameCinema(ct.getId());
			if(StringUtil.isEmpty(searchContent)){
				return zyContactsService.genViewObject(cts);
			}else{
				List<ZyContactsEntity> resultCts = new ArrayList<ZyContactsEntity>();
				for (ZyContactsEntity contact : cts) {
					if(contact.getCellphone1().contains(searchContent) || contact.getName().contains(searchContent)){
						resultCts.add(contact);
					}
				}
				ctVo = zyContactsService.genViewObject(resultCts);
			}
		}
		return ctVo;
	}

	@RequestMapping(params = "wxDetail")
	public ModelAndView goWxDetail(String id){
		ModelAndView mv = new ModelAndView("com/wx/personal_center/contacts/contact_detail");
		mv.addObject("contact",zyContactsService.get(ZyContactsEntity.class,id));
		return mv;
	}

	@RequestMapping(params = "wxAdd")
	public ModelAndView goWxAddl(){
		ModelAndView mv = new ModelAndView("com/wx/personal_center/contacts/contact_add");
		TSUser user = ResourceUtil.getSessionUserName();
		ZyContactsEntity contact = zyContactsService.findContactByUserName(user.getUserName());
		mv.addObject("contact",contact);
		return mv;
	}


	/**
	 * @author mhg
	 * 2018-6-8
	 * Description 将联系人对应的用户升价为金牌
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params="addGold")
	public AjaxJson addGold(HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		String id=request.getParameter("id");
		ZyContactsEntity contact =null;
		TSBaseUser baseUser=null;
		if(StringUtil.isNotEmpty(id)){
			contact=systemService.get(ZyContactsEntity.class,id);
		}
		try {
			if(contact!=null){
				if(contact.getTsBaseUser()!=null){
					baseUser=contact.getTsBaseUser();
					if(contact.getTsBaseUser().getAuthenticationLevel()!=null){
						if(baseUser.getAuthenticationLevel().equals("2") ){
							message="该用户已经是钻石用户，不能再认证金牌";
						}else if(baseUser.getAuthenticationLevel().equals("4") ){
							message="该用户已经是金牌用户";
						}else{
							baseUser.setAuthenticationLevel("4");
							systemService.saveOrUpdate(baseUser);
							message="认证成功";
							if(StringUtil.isNotEmpty(baseUser.getOpenId())){
								//调用微信接口，升级微信用户为金牌
								String jsonString=wxCommonService.noticeAddLevel(baseUser.getOpenId(),"PROMOTE_GOLD");
		                        //调用微信接口发送
		                        List<Map<String, String>> list = new ArrayList<>();
		                        if (StringUtil.isNotEmpty(baseUser.getOpenId())) {
		                            Map<String, String> map1 = new HashMap<>();
		                            map1.put("openid", baseUser.getOpenId());
		                            map1.put("message", "尊敬的客户，恭喜您升级为中影巴可金牌客户。");
		                            list.add(map1);
		                            wxCommonService.sendMsgForWx(list);
		                        }
							}
							j.setObj("success");
						}
					}else{
						baseUser.setAuthenticationLevel("4");
						systemService.saveOrUpdate(baseUser);
						if(StringUtil.isNotEmpty(baseUser.getOpenId())){
							//调用微信接口，升级微信用户为金牌
							String jsonString=wxCommonService.noticeAddLevel(baseUser.getOpenId(),"PROMOTE_GOLD");
	                        //调用微信接口发送
	                        List<Map<String, String>> list = new ArrayList<>();
	                        if (StringUtil.isNotEmpty(baseUser.getOpenId())) {
	                            Map<String, String> map1 = new HashMap<>();
	                            map1.put("openid", baseUser.getOpenId());
	                            map1.put("message", "尊敬的客户，恭喜您升级为中影巴可金牌客户。");
	                            list.add(map1);
	                            wxCommonService.sendMsgForWx(list);
	                        }
						}
						message="认证成功";
						j.setObj("success");
					}

				}else{
					message="请先创建用户";
				}
			}
		} catch (Exception e) {
			message = "升级失败";
			e.printStackTrace();
		}
		j.setMsg(message);
		return j;
	}

}
